package giftmail.interceptor;

import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import giftmail.model.User;
import giftmail.staticentity.SessionInfo;

public class SessionInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session=request.getSession();
		
		User sysUser = (User) session.getAttribute(SessionInfo.SESSION_LOGIN_USER);
		if (sysUser!=null) {
			return true;
		}
		
		//过滤Ajax请求
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
			return true;
		} else {
			alertMsgAndJumpToLoginPage(request, response);
		}

		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	private void alertMsgAndJumpToLoginPage(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");

			OutputStreamWriter out=new OutputStreamWriter(response.getOutputStream());

			String msg="由于您长时间没有操作，session已过期，请重新登录！";
			msg=new String(msg.getBytes("UTF-8"));

			out.write("<meta http-equiv='Content-Type' content='text/html';charset='UTF-8'>");
			out.write("<script>");
			out.write("alert('"+msg+"');");
			out.write("top.location.href = '" +request.getContextPath() + "/loginController/toLogin'; ");
			out.write("</script>");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
